<template>
  <div class="canvasBox" ref="canvasRef" :style="canvasStyle">
    <DragableBox class="dragableBox" v-for="(layer, index) in layers" :key="index" :w="layer.width" :h="layer.height" :x="layer.x" :y="layer.y" :angle="layer.rotation" :hasActiveContent="layer.type === 'text'" :dragHandler="onChange(layer)" :resizeHandler="onChange(layer)">
      <div class="delete" @click="deleteLayer(index)">×</div>
      <LayerBox :layerData="layer" style="width:100%;height:100%" />
    </DragableBox>
  </div>
</template>
<script>
// import CanvasController from '@/utils/CanvasController'
import { page } from '../../assets/js/mixin'
import DragableBox from './DragableBox.vue'
import LayerBox from './LayerBox.vue'
import html2canvas from 'html2canvas'

export default {
  name: 'canvasBox',
  props: {
    canvasStyle: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    DragableBox,
    LayerBox
  },
  mounted: function () {
    this.$store.state.canvasData.initCanvasSize(this.$refs.canvasRef.offsetWidth, this.$refs.canvasRef.offsetHeight)
    this.$on('saveImg', this.saveImg)
  },
  methods: {
    deleteLayer (index) {
      // index为所点击的图片在cavasData.layers中的位置
      this.canvasData.layers.splice(index, 1)
    },
    onChange: function (layer) {
      return function (r) {
        return layer.setRect(r)
      }
    },
    /**
     * 保存为图片，从父组件调用该方法时，在执行：
     * for (const child of this.$children) {
        child.$emit('saveImg')
       }
     */
    saveImg: function () {
      console.log('save')
      html2canvas(this.$refs.canvasRef, {
        allowTaint: true
      }).then(function (canvas) {
        let type = 'png'
        let imgData = canvas.toDataURL(type)
        let fileName = '页面' + '.png'
        let saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
        saveLink.href = imgData
        saveLink.download = fileName
        let fakeEvent = document.createEvent('MouseEvents')
        fakeEvent.initMouseEvent('click', true, false, window)
        saveLink.dispatchEvent(fakeEvent)
      })
    }
  },
  mixins: [page],
  computed: {
    layers () {
      return this.$store.state.canvasData.layers
    }
  }
}
</script>
<style scoped>
.canvasBox {
  margin: 10px auto;
  width: 614px;
  height: 908px;
  box-shadow: 0 0 10px 1px gray;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: center;
}
/* 素材删除样式 */
.delete {
  position: absolute;
  right: 0;
  top: 0;
  width: 1.65vw;
  height: 1.65vw;
  text-align: center;
  line-height: 1.65vw;
  font-size: 1.234vw;
  background-color: rgba(255, 255, 255, 0.5);
  user-select: none;
  cursor: pointer;
  opacity: 0;
  z-index: 99;
}
.delete:hover {
  opacity: 1;
  background-color: rgba(31, 31, 31, 0.5);
  color: white;
}
.imgUl > li:hover .delete {
  opacity: 1;
}
</style>
